/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.*;
import com.lczyfz.istep.modules.resource.service.*;
import com.lczyfz.istep.modules.sys.service.SystemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

/**
 * 试卷管理Controller
 * @author lsj
 *
 *
 *
 * @version 2017-01-15
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourcePaper")
public class ResourcePaperController extends BaseController {

	@Autowired
	private ResourcePaperService resourcePaperService;

	@Autowired
	private ResourceQuestionService resourceQuestionService;

	@Autowired
	private ResourcePaperQuestionService resourcePaperQuestionService;

	@Autowired
	private ResourceQuestionOptionService resourceQuestionOptionService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private ResourceRepertoryService resourceRepertoryService;
	
	@ModelAttribute
	public ResourcePaper get(@RequestParam(required=false) String id) {
		ResourcePaper entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourcePaperService.get(id);
		}
		if (entity == null){
			entity = new ResourcePaper();
		}
		return entity;
	}
	
	@RequiresPermissions("resource:resourcePaper:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourcePaper resourcePaper, HttpServletRequest request, HttpServletResponse response, Model model) {

		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");

		}
		else
		{
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourcePaper> page = resourcePaperService.findPage(new Page<ResourcePaper>(request, response), resourcePaper);
		model.addAttribute("page", page);
		return "modules/resource/resourcePaperList";
	}

	@RequiresPermissions("resource:resourcePaper:view")
	@RequestMapping(value = "form")
	public String form(ResourcePaper resourcePaper, Model model,String type){
//		logger.debug("resourceCourse=== [{}]",resourceCourse);
		ResourceQuestion resourceQuestion=new ResourceQuestion();
//		List<ResourceQuestion> resourceQuestionList=resourceQuestionService.findList(resourceQuestion);
//		List<ResourceQuestion> resourceQuestionList=resourceQuestionService.fionQuestionType("0");
		List<ResourceQuestion> resourceQuestionRadios = resourceQuestionService.fionQuestionType("0");
		List<ResourceQuestion> resourceQuestionCheckboxs = resourceQuestionService.fionQuestionType("1");
		List<ResourceQuestion> resourceQuestionJudements = resourceQuestionService.fionQuestionType("2");
		List<ResourceQuestion> resourceQuestionShortAnswers = resourceQuestionService.fionQuestionType("3");
		int count=0;
		if(resourcePaper!=null&&resourcePaper.getId()!=null&&!resourcePaper.getId().equals(""))
		{
			logger.debug("课程id [{}]", resourcePaper.getId());
			ResourcePaperQuestion resourcePaperQuestion=new ResourcePaperQuestion();
			resourcePaperQuestion.setPaperId(resourcePaper.getId());
			List<ResourcePaperQuestion> resourcePaperQuestionsList=resourcePaperQuestionService.findList(resourcePaperQuestion);
//			logger.debug("试卷问题中间表长度 [{}]",resourcePaperQuestionsList.size());
			for (int i = 0; i < resourceQuestionRadios.size(); i++)
			{
				if(resourcePaperQuestionsList.size()==0)
				{
					break;
				}else
				{


					for (int j = 0; j < resourcePaperQuestionsList.size(); j++)
					{
						if (resourceQuestionRadios.get(i).getId().equals(resourcePaperQuestionsList.get(j).getQuestionId()))
						{

							resourceQuestionRadios.get(i).setIsChoose("true");
							count++;


							resourcePaperQuestionsList.remove(j);
							break;
						}else
							resourceQuestionRadios.get(i).setIsChoose("false");
					}
				}

			}
			for (int i = 0; i < resourceQuestionCheckboxs.size(); i++) {
				if(resourcePaperQuestionsList.size()==0)
				{
					break;
				}else {


					for (int j = 0; j < resourcePaperQuestionsList.size(); j++) {
						if (resourceQuestionCheckboxs.get(i).getId().equals(resourcePaperQuestionsList.get(j).getQuestionId())) {

							resourceQuestionCheckboxs.get(i).setIsChoose("true");
							count++;


							resourcePaperQuestionsList.remove(j);
							break;
						}else
							resourceQuestionCheckboxs.get(i).setIsChoose("false");

//						if (j == resourcePaperQuestionsList.size() - 1) {
//							resourceQuestionList.get(i).setIsChoose("false");
//						}
					}
				}
			}
			for (int i = 0; i < resourceQuestionJudements.size(); i++) {
				if(resourcePaperQuestionsList.size()==0)
				{
					break;
				}else {


					for (int j = 0; j < resourcePaperQuestionsList.size(); j++) {
						if (resourceQuestionJudements.get(i).getId().equals(resourcePaperQuestionsList.get(j).getQuestionId())) {

							resourceQuestionJudements.get(i).setIsChoose("true");
							count++;


							resourcePaperQuestionsList.remove(j);
							break;
						}else
							resourceQuestionJudements.get(i).setIsChoose("false");

//						if (j == resourcePaperQuestionsList.size() - 1) {
//							resourceQuestionList.get(i).setIsChoose("false");
//						}
					}
				}
			}
			for (int i = 0; i < resourceQuestionShortAnswers.size(); i++) {
				if(resourcePaperQuestionsList.size()==0)
				{
					break;
				}else {


					for (int j = 0; j < resourcePaperQuestionsList.size(); j++) {
						if (resourceQuestionShortAnswers.get(i).getId().equals(resourcePaperQuestionsList.get(j).getQuestionId())) {

							resourceQuestionShortAnswers.get(i).setIsChoose("true");
							count++;


							resourcePaperQuestionsList.remove(j);
							break;
						}else
							resourceQuestionShortAnswers.get(i).setIsChoose("false");

//						if (j == resourcePaperQuestionsList.size() - 1) {
//							resourceQuestionList.get(i).setIsChoose("false");
//						}
					}
				}
			}

			List<ResourcePaperQuestion> resourcePaperQuestionList=resourcePaperQuestionService.findList(resourcePaperQuestion);
			logger.debug("试卷问题中间表长度 [{}]",resourcePaperQuestionList.size());
			for(int i=0;i<resourcePaperQuestionList.size();i++)
			{
				//根据问题id查询出问题类型列表
				ResourceQuestion resourceQuestion1 = new ResourceQuestion();
				resourceQuestion1.setId(resourcePaperQuestionList.get(i).getQuestionId());
				List<ResourceQuestion> resourceQuestionList = resourceQuestionService.findList(resourceQuestion1);
				logger.debug("问题列表长度[{}]" ,resourceQuestionList.size());
				logger.debug("第一个问题id是[{}]",resourcePaperQuestionList.get(i).getQuestionId());
				for(int j=0;j<resourceQuestionList.size();j++)
				{
					//如果是单选题 取第一个分值
					logger.debug("问题类型是[{}]",Integer.valueOf(resourceQuestionList.get(j).getQuestionType()));

					if (Integer.valueOf(resourceQuestionList.get(j).getQuestionType())== 0)
					{
						logger.debug("单选题的我进来了~");
						resourcePaperQuestion.setPaperId(resourcePaper.getId());
						resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
						List<ResourcePaperQuestion> resourcePaperQuestionListRadio = resourcePaperQuestionService.findList(resourcePaperQuestion);
						logger.debug("单选题列表的长度[{}]",resourcePaperQuestionListRadio.size());
						if(resourcePaperQuestionListRadio.size()!=0){
							model.addAttribute("radioScore", resourcePaperQuestionListRadio.get(0));
						}
					}

					//如果是多选题
					if (Integer.valueOf(resourceQuestionList.get(j).getQuestionType())== 1)
					{
						logger.debug("其实我已经进来了！");
						resourcePaperQuestion.setPaperId(resourcePaper.getId());
						resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
						List<ResourcePaperQuestion> resourcePaperQuestionListCheck = resourcePaperQuestionService.findList(resourcePaperQuestion);
						logger.debug("多选题列表长度[{}]",resourcePaperQuestionListCheck.size());
						if(resourcePaperQuestionListCheck.size()!=0){
							model.addAttribute("checkScore", resourcePaperQuestionListCheck.get(0));
							break;
						}

					}


					//如果是判断题
					if (Integer.valueOf(resourceQuestionList.get(j).getQuestionType())== 2)
					{
						logger.debug("判断题的我已经进来了 ");
						resourcePaperQuestion.setPaperId(resourcePaper.getId());
						resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
						List<ResourcePaperQuestion> resourcePaperQuestionListJudge = resourcePaperQuestionService.findList(resourcePaperQuestion);
						if(resourcePaperQuestionListJudge.size()!=0){
							model.addAttribute("judgeScore", resourcePaperQuestionListJudge.get(0));
						}
					}
					//如果是简答题
					if (Integer.valueOf(resourceQuestionList.get(j).getQuestionType())== 3)
					{
						logger.debug("简答题的我已经进来了~");
						resourcePaperQuestion.setPaperId(resourcePaper.getId());
						resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
						List<ResourcePaperQuestion> resourcePaperQuestionListShortAnswer = resourcePaperQuestionService.findList(resourcePaperQuestion);
						if(resourcePaperQuestionListShortAnswer.size()!=0){
							model.addAttribute("shortAnswerScore", resourcePaperQuestionListShortAnswer.get(0));
						}
					}

				}

			}


		}
		if(type!=null&&type.equals("copy"))
			{

				resourcePaper.setPaperName(resourcePaper.getPaperName() + "-副本");
			}
		if (systemService.isSuperAdmin()) {
			model.addAttribute("isSuperAdmin", "true");
		} else
			model.addAttribute("isSuperAdmin", "false");

		ResourceRepertory resourceRepertory = new  ResourceRepertory();
		List<ResourceRepertory> resourceRepertoryList = resourceRepertoryService.findList(resourceRepertory);
		//中间表对象
			ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
			//lishijin
			// 根据试卷id查到试卷问题中间表的列表。
			resourcePaperQuestion.setPaperId(resourcePaper.getId());
			logger.debug("试卷id是：",resourcePaper.getId());
			List<ResourcePaperQuestion> resourcePaperQuestionList = resourcePaperQuestionService.findList(resourcePaperQuestion);
			logger.debug("试卷问题中间表长度==",resourcePaperQuestionList.size());
//			for(int i=0;i<resourcePaperQuestionList.size();i++)
//			{
//					//根据问题id查询出问题类型列表
//					ResourceQuestion resourceQuestion1 = new ResourceQuestion();
//					resourceQuestion1.setId(resourcePaperQuestionList.get(i).getQuestionId());
//					List<ResourceQuestion> resourceQuestionList = resourceQuestionService.findList(resourceQuestion1);
//					logger.debug("问题列表长度==1 ?" ,resourceQuestionList.size());
//					for(int j=0;j<resourceQuestionList.size();j++)
//					{
//						//如果是单选题 取第一个分值
//						if (resourceQuestionList.get(j).getQuestionType().equals('0'))
//						{
//							resourcePaperQuestion.setPaperId(resourcePaperQuestion.getPaperId());
//							resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
//							List<ResourcePaperQuestion> resourcePaperQuestionListRadio = resourcePaperQuestionService.findList(resourcePaperQuestion);
//							logger.debug("单选题列表的长度==",resourcePaperQuestionListRadio.size());
//							if(resourcePaperQuestionListRadio.size()!=0){
//								model.addAttribute("radioScore", resourcePaperQuestionListRadio.get(0).getScore());
//							}
//						}
//
//						//如果是多选题
//						if (resourceQuestionList.get(j).getQuestionType().equals('1'))
//						{
//							resourcePaperQuestion.setPaperId(resourcePaperQuestion.getPaperId());
//							resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
//							List<ResourcePaperQuestion> resourcePaperQuestionListCheck = resourcePaperQuestionService.findList(resourcePaperQuestion);
//							if(resourcePaperQuestionListCheck.size()!=0){
//								model.addAttribute("checkScore", 1);
//							}
//						}
//
//
//						//如果是判断题
//						if (resourceQuestionList.get(j).getQuestionType().equals('2'))
//						{
//							resourcePaperQuestion.setPaperId(resourcePaperQuestion.getPaperId());
//							resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
//							List<ResourcePaperQuestion> resourcePaperQuestionListJudge = resourcePaperQuestionService.findList(resourcePaperQuestion);
//							if(resourcePaperQuestionListJudge.size()!=0){
//								model.addAttribute("judgeScore", resourcePaperQuestionListJudge.get(0).getScore());
//							}
//						}
//						//如果是简答题
//						if (resourceQuestionList.get(j).getQuestionType().equals('3'))
//						{
//							resourcePaperQuestion.setPaperId(resourcePaperQuestion.getPaperId());
//							resourcePaperQuestion.setQuestionId(resourceQuestionList.get(j).getId());
//							List<ResourcePaperQuestion> resourcePaperQuestionListShortAnswer = resourcePaperQuestionService.findList(resourcePaperQuestion);
//							if(resourcePaperQuestionListShortAnswer.size()!=0){
//								model.addAttribute("shortAnswerScore", resourcePaperQuestionListShortAnswer.get(0).getScore());
//							}
//						}
//
//					}

//			}

		if (resourcePaperQuestionList != null && resourcePaperQuestionList.size() != 0) {
			model.addAttribute("resourcePaperQuestion", resourcePaperQuestionList.get(0));
		}
//			model.addAttribute("resourceQuestionList", resourceQuestionList);
			model.addAttribute("resourceQuestionRadios", resourceQuestionRadios);
			model.addAttribute("resourceQuestionCheckboxs", resourceQuestionCheckboxs);
			model.addAttribute("resourceQuestionJudements", resourceQuestionJudements);
			model.addAttribute("resourceQuestionShortAnswers", resourceQuestionShortAnswers);

			model.addAttribute("type", type);
			model.addAttribute("resourcePaper", resourcePaper);
			model.addAttribute("resourceRepertoryList", resourceRepertoryList);
			return "modules/resource/resourcePaperForm";
	}

	@RequiresPermissions("resource:resourcePaper:edit")
	@RequestMapping(value = "save")
	public String save(ResourcePaper resourcePaper, Model model, RedirectAttributes redirectAttributes,String duallist,String type,
					   String checkboxDuallist,String shortAnswerDuallist,String judementDuallist,String score,String score1,String score2,String score3) {


		if (!beanValidator(model, resourcePaper)) {
			return form(resourcePaper, model, type);
		}

		logger.debug("duallist: [{}]", duallist);
		if (Integer.valueOf(resourcePaper.getPaperType()) == 1) {
			if (type != null && type.equals("copy")) {
				logger.debug("复制试卷！");
				ResourcePaper temp = resourcePaperService.findPaperByPaperName(resourcePaper);
				if (temp != null && temp.getPaperName().equals(resourcePaper.getPaperName())) {
					addMessage(redirectAttributes, "复制试卷'" + resourcePaper.getPaperName() + "'失败，该试卷已存在");
				} else {
					if (duallist == null || duallist.equals("")) {
						addMessage(redirectAttributes, "复制试卷失败，请选择需要的题目");
					} else {
						ResourcePaper resourcePaper1 = new ResourcePaper();
						resourcePaper1.setPaperName(resourcePaper.getPaperName());
						resourcePaper1.setPaperAttribute(resourcePaper.getPaperAttribute());
						resourcePaper1.setRemarks(resourcePaper.getRemarks());
						resourcePaper1.setPaperType(resourcePaper.getPaperType());
						resourcePaperService.save(resourcePaper1);
						resourcePaperQuestionService.save(duallist, resourcePaper1, score);
						resourcePaperQuestionService.save(checkboxDuallist, resourcePaper1, score1);
						resourcePaperQuestionService.save(judementDuallist, resourcePaper1, score2);
						resourcePaperQuestionService.save(shortAnswerDuallist, resourcePaper1, score3);
						addMessage(redirectAttributes, "复制试卷'" + resourcePaper.getPaperName() + "'成功");
					}
				}

			} else {
				if (resourcePaperService.get(resourcePaper) == null) {
					logger.debug("插入试卷！");
					ResourcePaper temp = resourcePaperService.findPaperByPaperName(resourcePaper);
					logger.debug("temp里面的内容是：" + temp);
//					ResourceQuestion resourceQuestion =
					if (temp != null && temp.getPaperName().equals(resourcePaper.getPaperName())) {
						addMessage(redirectAttributes, "添加试卷'" + resourcePaper.getPaperName() + "'失败，该试卷已存在");
					} else {
						if ((duallist == null || duallist.equals("")) && (checkboxDuallist == null || checkboxDuallist.equals("")) &&
								(judementDuallist == null || judementDuallist.equals("")) && (shortAnswerDuallist == null || shortAnswerDuallist.equals(""))) {
							addMessage(redirectAttributes, "添加试卷失败，请选择需要的题目");
						} else {
							int sum = 0;
							int totalsum =0;
							int count = 0;
							int experimentSum =0;
							String[] resourceQuestionList = new String[0];
							String[] resourceQuestionList1 = new String[0];
							String[] resourceQuestionList2 = new String[0];
							String[] resourceQuestionList3 = new String[0];
							if (duallist != null && !duallist.equals("")) {
								String a[] = duallist.split(",");
								sum = a.length * Integer.valueOf(score);

								totalsum+=a.length;
								resourceQuestionList = duallist.split(",");
								for (int i = 0; i < resourceQuestionList.length; i++) {
									ResourceQuestion resourceQuestion = resourceQuestionService.get(resourceQuestionList[i]);
									if (resourceQuestion.getEnvironmentId() != null && !resourceQuestion.getEnvironmentId().equals("")) {
										count++;
									}
								}
//								experimentSum+=count;
							}
							if (checkboxDuallist != null && !checkboxDuallist.equals("")) {

								String b[] = checkboxDuallist.split(",");
								sum += b.length * Integer.valueOf(score1);
								totalsum+= b.length;
								resourceQuestionList1 = checkboxDuallist.split(",");
								for (int i = 0; i < resourceQuestionList1.length; i++) {
									ResourceQuestion resourceQuestion = resourceQuestionService.get(resourceQuestionList1[i]);
									if (resourceQuestion.getEnvironmentId() != null && !resourceQuestion.getEnvironmentId().equals("")) {
										count++;
									}
								}
//								experimentSum+=count;
							}
							if (judementDuallist != null && !judementDuallist.equals("")) {
								String c[] = judementDuallist.split(",");
								sum += c.length * Integer.valueOf(score2);
								totalsum+=c.length;
								resourceQuestionList2 = judementDuallist.split(",");
								for (int i = 0; i < resourceQuestionList2.length; i++) {
									ResourceQuestion resourceQuestion = resourceQuestionService.get(resourceQuestionList2[i]);
									if (resourceQuestion.getEnvironmentId() != null && !resourceQuestion.getEnvironmentId().equals("")) {
										count++;
									}
								}
							}
							if (shortAnswerDuallist != null && !shortAnswerDuallist.equals("")) {
								String d[] = shortAnswerDuallist.split(",");
								sum += d.length * Integer.valueOf(score3);
								totalsum+=d.length;
								resourceQuestionList3 = shortAnswerDuallist.split(",");
								for (int i = 0; i < resourceQuestionList3.length; i++) {
									ResourceQuestion resourceQuestion = resourceQuestionService.get(resourceQuestionList3[i]);
									if (resourceQuestion.getEnvironmentId() != null && !resourceQuestion.getEnvironmentId().equals("")) {
										count++;
									}
								}
							}

							logger.debug("总分是：", sum);
							resourcePaper.setTotalScore(String.valueOf(sum));
							resourcePaper.setExperimentSum(count + "");
							resourcePaper.setQuestionSum(totalsum+"");
							resourcePaperService.save(resourcePaper);
							resourcePaperQuestionService.save(duallist, resourcePaper, score);
							resourcePaperQuestionService.save(checkboxDuallist, resourcePaper, score1);
							resourcePaperQuestionService.save(judementDuallist, resourcePaper, score2);
							resourcePaperQuestionService.save(shortAnswerDuallist, resourcePaper, score3);
							addMessage(redirectAttributes, "添加试卷'" + resourcePaper.getPaperName() + "'成功");
						}

					}
				} else {

					if ((duallist == null || duallist.equals("")) && (checkboxDuallist == null || checkboxDuallist.equals("")) &&
							(judementDuallist == null || judementDuallist.equals("")) && (shortAnswerDuallist == null || shortAnswerDuallist.equals(""))) {
						addMessage(redirectAttributes, "修改试卷失败，请选择需要的题目");
					} else {
						int s = 0;
						if (duallist != null && !duallist.equals("")) {
							String a[] = duallist.split(",");
							s = a.length * Integer.valueOf(score);
						}
						if (checkboxDuallist != null && !checkboxDuallist.equals("")) {
							String b[] = checkboxDuallist.split(",");
							s += b.length * Integer.valueOf(score1);
						}
						if (judementDuallist != null && !judementDuallist.equals("")) {
							String c[] = judementDuallist.split(",");
							s += c.length * Integer.valueOf(score2);
						}
						if (shortAnswerDuallist != null && !shortAnswerDuallist.equals("")) {
							String d[] = shortAnswerDuallist.split(",");
							s += d.length * Integer.valueOf(score3);
						}
						resourcePaper.setTotalScore(String.valueOf(s));
						resourcePaperService.save(resourcePaper);
						resourcePaperQuestionService.deleteByPaperId(resourcePaper);
						resourcePaperQuestionService.update(duallist, resourcePaper, score);
						resourcePaperQuestionService.update(checkboxDuallist, resourcePaper, score1);
						resourcePaperQuestionService.update(judementDuallist, resourcePaper, score2);
						resourcePaperQuestionService.update(shortAnswerDuallist, resourcePaper, score3);
						addMessage(redirectAttributes, "修改试卷'" + resourcePaper.getPaperName() + "'成功");
					}
				}
			}
		} else if (Integer.valueOf(resourcePaper.getPaperType()) == 2) {


			ArrayList<ResourceQuestion> list = new ArrayList<>();
			//拿到题库相应题目
			List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionReprtory(resourcePaper.getRepertoryId());
			// 随机单选题
			//总分
			int z_score = 0;
			if (StringUtils.isNotBlank(resourcePaper.getRadio_countNumber()) && resourcePaper.getRadio_options() != null && resourcePaper.getRadio_options().equals("0")) {
				if (resourcePaper.getRadioScore() != null) {
					z_score = z_score + (Integer.parseInt(resourcePaper.getRadioScore()) * Integer.parseInt(resourcePaper.getRadio_countNumber()));
				}
				//单选题单选题难度相应题目
				List<ResourceQuestion> resourceQuestions1 = new ArrayList<>();
				for (int j = 0; j < resourceQuestions.size(); j++) {
					if (resourceQuestions.get(j).getQuestionType().equals(resourcePaper.getRadio_options()) && resourceQuestions.get(j).getQuestionDifficulty().equals(resourcePaper.getRadio_difficulty()))
//						System.out.println("1------" + resourceQuestions.get(j).getQuestionScore() + "  " + resourceQuestions.get(j).getStem());
						resourceQuestions1.add(resourceQuestions.get(j));
				}
				if (Integer.parseInt(resourcePaper.getRadio_countNumber()) >= resourceQuestions1.size()) {
					for (ResourceQuestion resourceQuestion : resourceQuestions1) {
						resourceQuestion.setQuestionScore(resourcePaper.getRadioScore());
						list.add(resourceQuestion);
					}
				} else {
					Random ran = new Random();
					HashSet<Integer> set = new HashSet<>();
					while (true) {
						int a = ran.nextInt(resourceQuestions1.size());
						set.add(a);
						if (set.size() > Integer.valueOf(resourcePaper.getRadio_countNumber()) - 1) {
							break;
						}
					}
					for (int i : set) {
						resourceQuestions1.get(i).setQuestionScore(resourcePaper.getRadioScore());
						System.out.println("===========" + resourceQuestions1.get(i).getQuestionScore());
						list.add(resourceQuestions1.get(i));
					}
				}
			}


			if (resourcePaper.getCheckbox_countNumber() != null && !resourcePaper.getCheckbox_countNumber().equals("") && resourcePaper.getCheckbox_options() != null && resourcePaper.getCheckbox_options().equals("1")) {
				//多选题单选题难度相应题目


				if (resourcePaper.getCheckboxScore() != null) {
					z_score = z_score + (Integer.parseInt(resourcePaper.getCheckboxScore()) * Integer.parseInt(resourcePaper.getCheckbox_countNumber()));
				}
				List<ResourceQuestion> resourceQuestions1 = new ArrayList<ResourceQuestion>();
				for (int j = 0; j < resourceQuestions.size(); j++) {
					if (resourceQuestions.get(j).getQuestionType().equals(resourcePaper.getCheckbox_options()) && resourceQuestions.get(j).getQuestionDifficulty().equals(resourcePaper.getCheckbox_difficulty()))
						resourceQuestions1.add(resourceQuestions.get(j));
				}
				if (Integer.parseInt(resourcePaper.getCheckbox_countNumber()) >= resourceQuestions1.size()) {
					for (ResourceQuestion resourceQuestion : resourceQuestions1) {
						resourceQuestion.setQuestionScore(resourcePaper.getCheckboxScore());
						list.add(resourceQuestion);
					}
				} else {
					Random ran = new Random();
					HashSet<Integer> set = new HashSet<>();
					while (true) {
						int a = ran.nextInt(resourceQuestions1.size());
						set.add(a);
						if (set.size() > Integer.valueOf(resourcePaper.getCheckbox_countNumber()) - 1) {
							break;
						}
						if (set.size() > Integer.valueOf(resourcePaper.getCheckbox_countNumber()) - 1) {
							break;
						}
					}
					for (int i : set) {
						resourceQuestions1.get(i).setQuestionScore(resourcePaper.getCheckboxScore());
						list.add(resourceQuestions1.get(i));
					}
				}
			}


			if (resourcePaper.getJudement_countNumber() != null && !resourcePaper.getJudement_countNumber().equals("") && resourcePaper.getJudement_options() != null && resourcePaper.getJudement_options().equals("2")) {
				//判断题单选题难度相应题目
				if (resourcePaper.getJudementScore() != null) {
					z_score = z_score + (Integer.parseInt(resourcePaper.getJudementScore()) * Integer.parseInt(resourcePaper.getJudement_countNumber()));
				}
				List<ResourceQuestion> resourceQuestions1 = new ArrayList<>();
				for (int j = 0; j < resourceQuestions.size(); j++) {
					if (resourceQuestions.get(j).getQuestionType().equals(resourcePaper.getJudement_options()) && resourceQuestions.get(j).getQuestionDifficulty().equals(resourcePaper.getJudement_difficulty()))
						resourceQuestions1.add(resourceQuestions.get(j));
				}
				if (Integer.parseInt(resourcePaper.getJudement_countNumber()) >= resourceQuestions1.size()) {
					for (ResourceQuestion resourceQuestion : resourceQuestions1) {
						resourceQuestion.setQuestionScore(resourcePaper.getJudementScore());
						list.add(resourceQuestion);
					}
				} else {
					Random ran = new Random();
					HashSet<Integer> set = new HashSet<>();
					while (true) {
						int a = ran.nextInt(resourceQuestions1.size());
						set.add(a);
						if (set.size() > Integer.valueOf(resourcePaper.getJudement_countNumber()) - 1) {
							break;
						}
					}
					for (int i : set) {
						resourceQuestions1.get(i).setQuestionScore(resourcePaper.getJudementScore());
						list.add(resourceQuestions1.get(i));
					}
				}
			}

			if (resourcePaper.getShortAnswer_countNumber() != null && !resourcePaper.getShortAnswer_countNumber().equals("") && resourcePaper.getShortAnswer_options() != null && resourcePaper.getShortAnswer_options().equals("3")) {
				//简答题单选题难度相应题目
				if (resourcePaper.getShortAnswerScore() != null) {
					z_score = z_score + (Integer.parseInt(resourcePaper.getShortAnswerScore()) * Integer.parseInt(resourcePaper.getShortAnswer_countNumber()));
				}
				List<ResourceQuestion> resourceQuestions1 = new ArrayList<>();
				for (int j = 0; j < resourceQuestions.size(); j++) {
					if (resourceQuestions.get(j).getQuestionType().equals(resourcePaper.getShortAnswer_options()) && resourceQuestions.get(j).getQuestionDifficulty().equals(resourcePaper.getShortAnswer_difficulty()))
						resourceQuestions1.add(resourceQuestions.get(j));
				}
				if (Integer.parseInt(resourcePaper.getShortAnswer_countNumber()) >= resourceQuestions1.size()) {
					for (ResourceQuestion resourceQuestion : resourceQuestions1) {
						resourceQuestion.setQuestionScore(resourcePaper.getShortAnswerScore());
						list.add(resourceQuestion);
					}
				} else {
					Random ran = new Random();
					HashSet<Integer> set = new HashSet<>();
					while (true) {
						int a = ran.nextInt(resourceQuestions1.size());
						set.add(a);
						if (set.size() > Integer.valueOf(resourcePaper.getShortAnswer_countNumber()) - 1) {
							break;
						}
					}
					for (int i : set) {
						resourceQuestions1.get(i).setQuestionScore(resourcePaper.getShortAnswerScore());
						list.add(resourceQuestions1.get(i));
					}
				}
			}

			resourcePaper.setTotalScore(String.valueOf(z_score));


			if (type != null && type.equals("copy")) {
				logger.debug("复制试卷！");
				ResourcePaper temp = resourcePaperService.findPaperByPaperName(resourcePaper);
				if (temp != null && temp.getPaperName().equals(resourcePaper.getPaperName())) {
					addMessage(redirectAttributes, "复制试卷'" + resourcePaper.getPaperName() + "'失败，该试卷已存在");
				} else {


					ResourcePaper resourcePaper1 = new ResourcePaper();
					resourcePaper1.setPaperName(resourcePaper.getPaperName());
					resourcePaper1.setPaperAttribute(resourcePaper.getPaperAttribute());
					resourcePaper1.setRemarks(resourcePaper.getRemarks());
					resourcePaper1.setPaperType(resourcePaper.getPaperType());
					resourcePaperService.save(resourcePaper1);
					resourcePaperQuestionService.save(duallist, resourcePaper1, score);
				/*	resourcePaperQuestionService.save(checkboxDuallist, resourcePaper1, score1);
					resourcePaperQuestionService.save(judementDuallist, resourcePaper1, score2);
					resourcePaperQuestionService.save(shortAnswerDuallist, resourcePaper1, score3);*/
					addMessage(redirectAttributes, "复制试卷'" + resourcePaper.getPaperName() + "'成功");

				}
			} else {
				if (resourcePaperService.get(resourcePaper) == null) {
					logger.debug("插入试卷！");

					ResourcePaper temp = resourcePaperService.findPaperByPaperName(resourcePaper);
					logger.debug("temp里面的内容是：" + temp);
					if (temp != null && temp.getPaperName().equals(resourcePaper.getPaperName())) {
						addMessage(redirectAttributes, "添加试卷'" + resourcePaper.getPaperName() + "'失败，该试卷已存在");
					} else {
						if (list.size() == 0) {
							addMessage(redirectAttributes, "添加试卷失败，请选择需要的题目");
						} else {

							resourcePaperService.save(resourcePaper);
							logger.debug("duallist [{}]", duallist);
							logger.debug("课程id [{}]", resourcePaper.getId());
							logger.debug("中间表服务 [{}]", resourcePaperQuestionService);
							resourcePaperQuestionService.saveRandom(list, resourcePaper);
							addMessage(redirectAttributes, "添加试卷'" + resourcePaper.getPaperName() + "'成功");
						}

					}
				} else {
					if (list.size() == 0) {
						addMessage(redirectAttributes, "修改试卷失败，请选择需要的题目");
					} else {
						logger.debug("duallist的值是：" + duallist);
						resourcePaperService.save(resourcePaper);
						resourcePaperQuestionService.update(duallist, resourcePaper, score);
//						resourcePaperQuestionService.update(checkboxDuallist, resourcePaper, score1);
//						resourcePaperQuestionService.update(judementDuallist, resourcePaper, score2);
//						resourcePaperQuestionService.update(shortAnswerDuallist, resourcePaper, score3);
						addMessage(redirectAttributes, "修改试卷'" + resourcePaper.getPaperName() + "'成功");
					}
				}


			}

		}
		return "redirect:" + Global.getAdminPath() + "/resource/resourcePaper/?repage";
	}
	@RequiresPermissions("resource:resourcePaper:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourcePaper resourcePaper, RedirectAttributes redirectAttributes) {
		resourcePaperService.delete(resourcePaper);
		addMessage(redirectAttributes, "删除试卷管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourcePaper/?repage";
	}

	/**
	 * 根据培训方案id查询试卷列表列表展示
	 * @param resourcePaper
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = "findPageByTrainprogramId")
	public String findPageByTrainprogramId(ResourcePaper resourcePaper, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("courseId=== [{}]", resourcePaper.getTrainprogramId());
		Page<ResourcePaper> page = resourcePaperService.findPageByTrainprogramId(new Page<ResourcePaper>(request, response), resourcePaper);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		model.addAttribute("page", page);
		return "modules/resource/resourcePaperList";
	}

	//根据试卷属性获取题目
		@ResponseBody
		@RequestMapping(value = "findPaperListByAttribute")
		public JsonModel findPaperListByAttribute(@RequestParam(required = false) String attribute) {
			logger.debug("==dingh==" + attribute);
			JsonModel jsonModel = new JsonModel();
			ResourceQuestion resourceQuestion=new ResourceQuestion();
			resourceQuestion.setQuestionAttribute(attribute);
			List<ResourceQuestion> resourceQuestionList = resourceQuestionService.findList(resourceQuestion);
			logger.debug("lsj" + resourceQuestionList.size());
			jsonModel.setDataObj(resourceQuestionList);
			return jsonModel;
		}
//	public String findQuestionListByAttribute(@RequestParam(required = false) String attribute) {
//		Page<ResourceCourse> page = resourceCourseService.findPageByCoursesystemId(new Page<ResourceCourse>(request, response), resourceCourse);
//		logger.debug("page.getList().size()=== [{}]", page.getList().size());
//		model.addAttribute("page", page);
//		return "modules/resource/resourceCourseList";
//	}
//	查看试卷详情
	@RequiresPermissions("resource:resourcePaper:edit")
	@RequestMapping(value = "detail")
	public String detail(ResourcePaper resourcePaper, Model model, HttpServletRequest request, HttpServletResponse response) {

		ResourceQuestion resourceQuestion=new ResourceQuestion();
		resourceQuestion.setPaperId(resourcePaper.getId());


		Page<ResourceQuestion> page = resourceQuestionService.findPageByPaperId(new Page<ResourceQuestion>(request, response), resourceQuestion);
		model.addAttribute("page", page);

		if (StringUtils.isNotBlank(resourcePaper.getPaperType())) {
			if (resourcePaper.getPaperType().equals("1")) {
				resourcePaper.setPaperType("0");
			}
			if (resourcePaper.getPaperType().equals("2")) {
				resourcePaper.setPaperType("1");
			}
		}
		model.addAttribute("resourceQuestion", resourceQuestion);
		model.addAttribute("resourcePaper", resourcePaper);
		return "modules/resource/resourcePaperDetail";
	}

	/**
	 * 试卷预览，
	 */

	@RequiresPermissions("resource:resourcePaper:view")
	@RequestMapping(value = "view")
	public String view(ResourcePaper resourcePaper, Model model,String id) {

		//根据试卷id生成试卷预览
		logger.debug("resourcePaperId=== [{}]", resourcePaper.getId());

		List<ResourceQuestion> resourceQuestionListRadio = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListCheckbox = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListJudement = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListShortAnswer = new ArrayList<ResourceQuestion>();
		ResourcePaper paper = resourcePaperService.get(id);
		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
		resourcePaperQuestion.setPaperId(id);

		logger.debug("resourcePaperQuestion.setPaperId(id)", resourcePaperQuestion.getPaperId());

		List<ResourcePaperQuestion> paperQuestions = resourcePaperQuestionService.findList(resourcePaperQuestion);
		logger.debug("lsjj===paperQuestions=",paperQuestions);
		//单选题
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==0) {
				resourceQuestionListRadio.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListRadio)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

		//多选题
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==1) {
				resourceQuestionListCheckbox.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListCheckbox)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//			判断题
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==2) {
				resourceQuestionListJudement.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListJudement)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//		简答题
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==3) {
				resourceQuestionListShortAnswer.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListShortAnswer)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//
//		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
//		List<ResourcePaperQuestion> resourcePaperQuestionsList = resourcePaperQuestionService.findList(resourcePaperQuestion);
//		for(ResourcePaperQuestion question:resourcePaperQuestionsList)
//		{
//			ResourceQuestionOption option = new ResourceQuestionOption();
//			option.setQuestionId(question.getId());
//			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
//
//		}

		model.addAttribute("resourceQuestionListRadio",resourceQuestionListRadio);
		model.addAttribute("resourceQuestionListCheckbox",resourceQuestionListCheckbox);
		model.addAttribute("resourceQuestionListJudement",resourceQuestionListJudement);
		model.addAttribute("resourceQuestionListShortAnswer",resourceQuestionListShortAnswer);

		model.addAttribute("resourcePaper", resourcePaper);
		return "modules/resource/resourcePaperView";
	}




	@ResponseBody
	@RequestMapping(value = "lists")
	public int  lists(String repertoryId,String options, String difficulty , String a) {
		int b = 0;
//		System.out.println(repertoryId +"---"+ options + "---" + difficulty + "---" + a);
		//拿到题库相应题目
		List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionReprtory(repertoryId);
		List<ResourceQuestion> resourceQuestions1 = new ArrayList<ResourceQuestion>();
		for (int j = 0; j < resourceQuestions.size(); j++) {
			if (resourceQuestions.get(j).getQuestionType().equals(options) && resourceQuestions.get(j).getQuestionDifficulty().equals(difficulty)){
				resourceQuestions1.add(resourceQuestions.get(j));
			}
		}
		if (Integer.parseInt(a) > resourceQuestions1.size()){
			b = 1;
		}
		return b;
	}






	@ResponseBody
	@RequestMapping(value = "findCourseListByAttribute")
	public JsonModel findCourseListByAttribute(@RequestParam(required = false) String attribute) {
		logger.debug("==lsj单选题==" + attribute);

		JsonModel jsonModel = new JsonModel();

		List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionType(attribute);

		System.out.println("---单选题" + resourceQuestions.size());

		jsonModel.setDataObj(resourceQuestions);
		return jsonModel;
	}

	@ResponseBody
	@RequestMapping(value = "findCourseListByAttribute1")
	public JsonModel findCourseListByAttribute1(@RequestParam(required = false) String attribute) {
		logger.debug("==lsj复选框==" + attribute);

		JsonModel jsonModel = new JsonModel();

		List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionType(attribute);

		System.out.println("---复选框" + resourceQuestions.size());

		jsonModel.setDataObj(resourceQuestions);
		return jsonModel;
	}

	@ResponseBody
	@RequestMapping(value = "findCourseListByAttribute2")
	public JsonModel findCourseListByAttribute2(@RequestParam(required = false) String attribute) {
		logger.debug("==lsj判断题==" + attribute);

		JsonModel jsonModel = new JsonModel();

		List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionType(attribute);

		System.out.println("---判断题" + resourceQuestions.size());

		jsonModel.setDataObj(resourceQuestions);
		return jsonModel;
	}

	@ResponseBody
	@RequestMapping(value = "findCourseListByAttribute3")
	public JsonModel findCourseListByAttribute3(@RequestParam(required = false) String attribute) {
		logger.debug("==lsj简答题==" + attribute);

		JsonModel jsonModel = new JsonModel();

		List<ResourceQuestion> resourceQuestions = resourceQuestionService.fionQuestionType(attribute);

		System.out.println("---简答题" + resourceQuestions.size());

		jsonModel.setDataObj(resourceQuestions);
		return jsonModel;
	}










}